package com.yyz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yyz.domain.Category;
import com.yyz.exception.CustomException;
import com.yyz.mapper.CategoryMapper;
import com.yyz.service.CategoryService;
import com.yyz.service.DishService;
import com.yyz.service.SetMealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author yyz
 * @create 2023-07-20 14:58
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private DishService dishService;

    @Autowired
    private SetMealService setMealService;

    /**
     * 添加菜品分类
     *
     * @param category
     */
    @Override
    public void insert(Category category) {
        categoryMapper.insert(category);
    }

    /**
     * 分页查询菜品信息
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public IPage<Category> pageList(Integer page, Integer pageSize) {
        IPage<Category> pageInfo = new Page<>(page, pageSize);

        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.orderByAsc(Category::getSort);

        categoryMapper.selectPage(pageInfo, lqw);

        return pageInfo;
    }

    /**
     * 修改菜品
     *
     * @param category
     */
    @Override
    public void update(Category category) {
        categoryMapper.updateById(category);
    }

    /**
     * 删除分类
     *
     * @param ids
     */
    @Override
    public void delete(Long ids) {
        //判定该菜品分类是否关联了菜品
        Integer DishCount = dishService.count(ids);
        if (DishCount > 0) {
            //关联了菜品抛出异常
            throw new CustomException("该菜品分类关联了其他菜品无法删除！");
        }

        //判定该套餐分类是否关联了套餐
        Integer SetMealCount = setMealService.count(ids);
        if (SetMealCount > 0) {
            //关联了菜品抛出异常
            throw new CustomException("该套餐分类关联了其他套餐无法删除！");
        }

        //都没关联正常删除
        categoryMapper.deleteById(ids);
    }

    /**
     * 菜品分类下拉框
     *
     * @param category
     * @return
     */
    @Override
    public List<Category> list(Category category) {
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(category.getType() != null, Category::getType, category.getType());
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        List<Category> list = categoryMapper.selectList(lqw);
        return list;
    }


}
